package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Part;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Option;
import com.sl.au.service.PartService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartBaseInfoService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 部件绑定部件层级
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/bindingpart")
public class BindingPartController extends BaseController {

	@Autowired
	PartService partService;
	
	@Autowired
	PartBaseInfoService partBaseInfoService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	IdentifyService identifyService;
	
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("partBaseInfo/bindingpart");
		List<Option> options = optionService.getRepository().findByGroup("部件状态");
		modelAndView.addObject("options", options);
		return modelAndView;
	}
	
	/**
	 * 获取部件区域树信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		List<Part> node = null;
		
		node = partService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=partService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取绑定部件层级的信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<PartBaseInfo> modules=null;
		int count = 0;
		
		modules = partBaseInfoService.getPageByNoPart(start, length, key, "createTime", Sort.Direction.DESC);
		count = partBaseInfoService.getCountByNoPart(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 获取已绑定部件层级的信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpagebypart", method = RequestMethod.POST)
	public Map<String,Object> getPageByPart(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String partId=request.getParameter("partId");
		List<PartBaseInfo> modules=null;
		int count = 0;
		modules = partBaseInfoService.getPageByPart(start, length, partId, key, "createTime", Sort.Direction.DESC);
		count = partBaseInfoService.getCountByPart(partId, key);
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	
	/**
	 * 绑定部件层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/binding",method = RequestMethod.POST)
	public MsgHelper bindingPart(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = MsgHelper.success();
		String id = (String) map.get("id");
		String partId = String.valueOf(map.get("partId"));
		
		
//		int orderNum = partBaseInfoService.getRepository().getPartBaseInfoOrderByPart(partId);
		int orderNum = identifyService.getPartBaseInfoOrderByPart(partId);
		if(orderNum < 1000) {
			
			PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(id);
			Part part = partService.getRepository().findOne(partId);
//			String partIdentify = partService.getPartIdentify(partId);
			String partIdentify = identifyService.getIdentifyByType(partId,"partShow","part");
			String formatOrderNum = String.format("%03d",orderNum);
			partIdentify += formatOrderNum;
		
			partBaseInfo.setPart(part);
			partBaseInfo.setPartOrderNum(orderNum);
			partBaseInfo.setPartIdentify(partIdentify);
		
			partBaseInfoService.getRepository().save(partBaseInfo);
			msgHelper.setMsg("部件绑定成功!");
		}else {
			msgHelper.setCode(0);
			msgHelper.setMsg("该层级已绑定满，绑定失败！");
		}
		return msgHelper;
	};
	
	/**
	 * 解除绑定部件层级管理
	 * @param id
	 * @return
	 */
	@RequestMapping("/unbind/{id}")
	public MsgHelper unbindPart(@PathVariable("id") String id) {
		MsgHelper msgHelper = MsgHelper.success();
		PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(id);
		partBaseInfo.setPartOrderNum(0);
		partBaseInfo.setPart(null);
		partBaseInfo.setPartIdentify(null);
		partBaseInfoService.getRepository().save(partBaseInfo);
		msgHelper.setMsg("部件移除成功!");
		return msgHelper;
	}
	
	/**
	 * 保存视频部件扩展信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/bindvideoinfo",method = RequestMethod.POST)
	public MsgHelper saveVideoInfo(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = MsgHelper.success();
		String id = (String) map.get("id");
		String partId = String.valueOf(map.get("partId"));
		String interfaceAddress = String.valueOf(map.get("interfaceAddress"));
		String interfacePort = String.valueOf(map.get("interfacePort"));
		int orderNum = identifyService.getPartBaseInfoOrderByPart(partId);
		if(orderNum < 1000) {
			PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(id);
			Part part = partService.getRepository().findOne(partId);
	//		String partIdentify = partService.getPartIdentify(partId);
			String partIdentify = identifyService.getIdentifyByType(partId,"partShow","part");
	//		int orderNum = partBaseInfoService.getRepository().getPartBaseInfoOrderByPart(partId);
			
			String formatOrderNum = String.format("%03d",orderNum);
			partIdentify += formatOrderNum;
			
			partBaseInfo.setPart(part);
			partBaseInfo.setPartOrderNum(orderNum);
			partBaseInfo.setPartIdentify(partIdentify);
			partBaseInfo.setInterfaceAddress(interfaceAddress);
			partBaseInfo.setInterfacePort(interfacePort);
			partBaseInfoService.getRepository().save(partBaseInfo);
			msgHelper.setMsg("部件绑定成功!");
			
		}else {
			msgHelper.setCode(0);
			msgHelper.setMsg("该层级已绑定满，绑定失败！");
		}
		
		return msgHelper;
	};
	
	/**
	 * 更新部件数据信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper savePartBaseInfo(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = MsgHelper.success();
		String id = (String) map.get("id");
		String partType = String.valueOf(map.get("partType"));
		PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(id);
		
		if(partType.equals("1")) {
			String interfaceAddress = String.valueOf(map.get("interfaceAddress"));
			String interfacePort = String.valueOf(map.get("interfacePort"));
			partBaseInfo.setInterfaceAddress(interfaceAddress);
			partBaseInfo.setInterfacePort(interfacePort);
			partBaseInfoService.getRepository().save(partBaseInfo);
		}
		
		
		return msgHelper;
	};
	
	/**
	 * 保存部件信息及上传图标
	 * @param partBaseInfo
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "savePartBaseInfoWithFile", method = RequestMethod.POST)
	public Map<String, Object> saveDetailWithFile(PartBaseInfo partBaseInfo,@RequestParam(value = "file", required = false) MultipartFile file) {
		Map<String, Object> map = new HashMap<String, Object>();
//		Map<String, String[]> info = request.getParameterMap();
//		String sInstallationTime = info.get("installation")[0] + " 00:00:00";
//		String sProductionTime = info.get("production")[0] + " 00:00:00";
//		String pattern = "yyyy-MM-dd HH:mm:ss";
//		Date installationTime = ExdeUtil.str2Date(sInstallationTime, pattern);
//		Date productionTime = ExdeUtil.str2Date(sProductionTime, pattern);
//		partBaseInfo.setInstallationTime(installationTime);
//		partBaseInfo.setProductionTime(productionTime);
		
		PartBaseInfo oldPartBaseInfo = partBaseInfoService.getRepository().findOne(partBaseInfo.getId());
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadIconFilePath(this.fileUploadPath, "icon/PartBaseInfo", file);
			oldPartBaseInfo.setIconAddress(url);
		}
		
		oldPartBaseInfo.setDeviceIdentify(partBaseInfo.getDeviceIdentify());
		oldPartBaseInfo.setPartName(partBaseInfo.getPartName());
		oldPartBaseInfo.setManufacturer(partBaseInfo.getManufacturer());
		oldPartBaseInfo.setProductionTime(partBaseInfo.getProductionTime());
		oldPartBaseInfo.setInstallationTime(partBaseInfo.getInstallationTime());
		oldPartBaseInfo.setState(partBaseInfo.getState());
		oldPartBaseInfo.setInterfaceAddress(partBaseInfo.getInterfaceAddress());
		oldPartBaseInfo.setInterfacePort(partBaseInfo.getInterfacePort());
	        
		partBaseInfoService.getRepository().save(oldPartBaseInfo);
		//partBaseInfo=partBaseInfoService.savePartBaseInfo(partBaseInfo);
		
		map.put("code", 1);
		return map;
	}
	
	@RequestMapping(value="/addDataAll",method = RequestMethod.POST)
	public Map<String,Object> addDataAll(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String Id = (String) map.get("Id");
		ArrayList<String> dataInfo = (ArrayList<String>) map.get("dataInfo");
		Part part = partService.getRepository().findOne(Id);
		String partIdentify = identifyService.getIdentifyByType(Id,"partShow","part");
//		int orderNum = partBaseInfoService.getRepository().getPartBaseInfoOrderByPart(Id);
		int orderNum = identifyService.getPartBaseInfoOrderByPart(Id);
		boolean flag = false;
		for(String partBaseInfoId : dataInfo) {
			if(orderNum < 1000) {
				PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(partBaseInfoId);
				partBaseInfo.setPartOrderNum(orderNum);
				String formatOrderNum = String.format("%03d",orderNum++);
				String partIdentifyTemp = "";
				partIdentifyTemp = partIdentify + formatOrderNum;
				partBaseInfo.setPart(part);
				partBaseInfo.setPartIdentify(partIdentifyTemp);
				partBaseInfoService.getRepository().save(partBaseInfo);
			}else {
				flag = true;
				break;
			}
		}
		if(flag) {
			msg.put("msg", "该层级已绑定满，绑定失败！");
		}else {
			msg.put("msg", "部件绑定成功!");
		}
		return msg;
	};
	
	@RequestMapping(value="/removeDataAll",method = RequestMethod.POST)
	public Map<String,Object> removeDataAll(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		ArrayList<String> dataInfo = (ArrayList<String>) map.get("dataInfo");
		for(String partBaseInfoId : dataInfo) {
			PartBaseInfo partBaseInfo = partBaseInfoService.getRepository().findOne(partBaseInfoId);
			partBaseInfo.setPartOrderNum(0);
			partBaseInfo.setPart(null);
			partBaseInfo.setPartIdentify(null);
			partBaseInfoService.getRepository().save(partBaseInfo);
		}
		msg.put("msg", "部件移除成功!");
		return msg;
	};
}
